<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\service;



use app\common\model\system\SysResource;
use app\common\enum\FileEnum;
use app\common\enum\SysEnum;
use think\facade\Config;
use app\common\model\system\SysStorage;
use Exception;
class UploadService
{
    private  string $default;
    private  array $disks;
    private  array $file;

    public function __construct($default = '')
    {
        $config = Config::get('filesystem'); //系统配置
        $this->default = $default ?: $config['default'];
        $this->disks = $config['disks'];
        $this->file = $config['file'];

    }

    /**
     * @notes 上传图片


     */
    public  function image(string $saveDir = 'uploads/images')
    {
      //  try {
            //获取启用的存储配置
            $config =SysStorage::where('status',1)->find()->toArray();
            // 2、执行文件上传
            $StorageDriver =new $this->disks[$this->default]['driver']($config);
            $StorageDriver->setUploadFile('file');
            $fileName = $StorageDriver->getFileName();
            $fileInfo = $StorageDriver->getFileInfo();

            $suffix = strtolower(strstr($fileInfo['name'], '.'));
            if (!in_array($suffix, explode(',', $this->file['suffix']))) {
                tips('系统不支持' . $suffix . '格式');
            }
            // 上传文件
            $saveDir = $saveDir . '/' .  date('Ymd');

            if (!$StorageDriver->upload($saveDir)) {
                tips($StorageDriver->getError());
            }

            // 3、处理文件名称
            if (strlen($fileInfo['name']) > 128) {
                $name = substr($fileInfo['name'], 0, 123);
                $nameEnd = substr($fileInfo['name'], strlen($fileInfo['name'])-5, strlen($fileInfo['name']));
                $fileInfo['name'] = $name . $nameEnd;
            }
            // 4、写入数据库中
            $url = $saveDir . '/' . str_replace("\\","/", $fileName);

            $res =  ['fileName'=>$fileInfo['name'], 'url' =>  $url,
                'src' => $config['domain']. $url,'suffix'=>$suffix,'size'=>$fileInfo['size']];
            return $res;
       // } catch (Exception $e) {
       //     throw new Exception($e->getMessage());
       // }
    }
    
   


}